package _17_剑指Offer;

import _17_剑指Offer.datastrcute.ListNode;

public class _18_剑指Offer删除链表的节点 {

    // 删除链表节点 （迭代）
    public ListNode deleteNode(ListNode head, int val) {
        ListNode prev = null;
        ListNode newHead = head;
        while (newHead != null) {
            if (newHead.val == val) {
                if (prev == null) {
                    head = head.next;
                } else {
                    prev.next = newHead.next;
                }
            }
            prev = newHead;
            newHead = newHead.next;
        }
        return head;
    }

    // 删除链表的节点 (递归)
    public ListNode deleteNode1(ListNode head, int val) {
        if (head == null) return null;

        head.next = deleteNode1(head.next, val);

        return head.val == val ? head.next : head;
    }


}
